from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings
from apps.users.models import User


def generate_email_verify_url(user):
    s = Serializer(settings.SECRET_KEY, expires_in=24 * 3600)
    data = {'user_id': user.id, 'email': user.email}
    token = s.dumps(data).decode()  # 序列化之后的数据类型为字节类型，一定要记得decode()
    verify_url = settings.EMAIL_VERIFY_URL + token
    return verify_url


def check_email_verify_url(token):
    s = Serializer(settings.SECRET_KEY, expires_in=24 * 3600)
    try:
        data = s.loads(token)
    except BadData:
        return None
    user_id = data.get('user_id')
    email = data.get('email')
    try:
        user = User.objects.get(id=user_id, email=email)
    except User.DoesNotExist:
        return None
    return user